import { View, Text } from "@tarojs/components";
import Taro, { useLoad } from "@tarojs/taro";
import MyInput from "@/components/MyInput";
import { Checkbox } from "@taroify/core";
import { useState } from "react";
import { registerApi, loginApi } from "@/api";
import { setUser, setToken } from "@/utils/auth";
import { toast } from "@/utils";

export default function Index() {
  const [checked, setChecked] = useState(false);
  const [account, setAccount] = useState("");
  const [pwd, setPwd] = useState("");
  useLoad(() => {
    console.log("Page loaded.");
  });
  const router = (url) => Taro.navigateTo({ url });
  const gotoIndex = () => Taro.switchTab({ url: "/pages/index/index" });

  function login() {
    if (!checked) return toast("请先同意用户协议");
    if (!account) return toast("请输入手机号或邮箱");
    if (!pwd) return toast("请输入密码");
    loginApi({ account, pwd }).then((res) => {
      setUser(res);
      toast("登陆成功", "success", 2000);
      setTimeout(() => gotoIndex(), 2000);
    });
  }

  return (
    <View className=" px-8">
      <Text onClick={gotoIndex}>Hello world!</Text>
      <View className="flex flex-col gap-4 mt-32">
        <MyInput placeholder="请输入手机号或密码" change={setAccount} />
        <MyInput placeholder="请输入密码" type="password" change={setPwd} />
      </View>
      <View className="flex text-gray-400 flex-col justify-center items-center gap-2 my-5">
        <View onClick={() => router("/pages/user/register")}>点击注册账号</View>
        <View
          onClick={login}
          className="w-full  text-center py-2 bg-[#73D0EF] text-white rounded-lg"
        >
          登录
        </View>
        <View onClick={gotoIndex}>我先逛逛</View>
      </View>
      <View className="flex justify-center items-center">
        <Checkbox
          shape="square"
          onChange={setChecked}
          checked={checked}
          size={20}
        >
          <View className="text-xs">
            已经阅读并同意
            <Text className="text-[#7896BC]">《用户服务协议》</Text>
          </View>
        </Checkbox>
      </View>
      <View className="flex justify-center items-center mt-8">
        <View className="bg-[#56BD6A] w-40 py-2 text-sm rounded-full text-center text-white">
          一键登录
        </View>
      </View>
    </View>
  );
}
